﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using BrokerBase.Lib.Product;
using Telerik.Windows.Controls;
using BrokerBase.Lib.Base;
using BrokerBase.Lib.Core;
using BrokerBase.Lib.Query;
using BrokerBase.Lib.Company;
using Broker.View.Comm;
using NHibernate;
using NHibernate.Criterion;

namespace Broker.View.ProductView
{
    /// <summary>
    /// ProductListPage.xaml 的交互逻辑
    /// </summary>
    public partial class ProductListPage
    {
        private const int PAGE_SIZE = 15;

        private PagingQuery pageingQuery;

        private string hqlBase = "from Product as p where 1=1 ";



        private IList<Order> orders = new List<Order>() { new Order("Company", true), new Order("Name", true) };


        public ProductListPage():base()
        {
            InitializeComponent();

            dpList.PageSize = PAGE_SIZE;
            Loaded += new RoutedEventHandler(ProductListPage_Loaded);

        }

        

        void ProductListPage_Loaded(object sender, RoutedEventArgs e)
        {
            SetButtonVisibility();
            SetOperRight();
            LoadCompanies();

            dpList.PageSize = PAGE_SIZE;

            if (LibGlobal.AppType == AppType.Business)
                rbtChecked.IsChecked = true;
            else
                rbtAll.IsChecked = true;

            if (PageModel == ListPageModel.Select)
            {
                BuildQuery();
                Query();
            }

        }

        public ListPageModel PageModel { get; set; }

        public IProduct SelectedItem { get; set; }

        public IEnumerable<IProduct> SelectedItems { get; set; }

        public RadWindow Owner { get; set; }

        private void SetButtonVisibility()
        {
            if (PageModel == ListPageModel.List)
            {
                btnConfirm.Visibility = Visibility.Collapsed;
                btnExit.Visibility = Visibility.Collapsed;
            }
            else
            {
                btnConfirm.Visibility = Visibility.Visible;
                btnExit.Visibility = Visibility.Visible;
            }
        }

        public IProduct SelectByHQL(string hql, ContentControl owner, double height, double width)
        {
            this.hqlBase = hql;

            PageModel = ListPageModel.Select;

            

            RadWindow w = new RadWindow();

            w.Header = "产品资料";

            w.Owner = owner;
            w.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            w.Height = height;
            w.Width = width;

            Frame f = new Frame();

            f.Content = this;

            w.Content = f;
            this.Owner = w;
            w.ShowDialog();

            

            return SelectedItem;
        }

        public IEnumerable<IProduct> MultiSelectByHQL(string hql, ContentControl owner, double height, double width)
        {
            this.hqlBase = hql;

            PageModel = ListPageModel.Select;

            gvProduct.SelectionMode = SelectionMode.Multiple;

            RadWindow w = new RadWindow();

            w.Header = "产品资料";

            w.Owner = owner;
            w.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            w.Height = height;
            w.Width = width;

            Frame f = new Frame();

            f.Content = this;

            w.Content = f;
            this.Owner = w;
            w.ShowDialog();

            return SelectedItems;
        }

        private void dpList_PageIndexChanged(object sender, Telerik.Windows.Controls.PageIndexChangedEventArgs e)
        {
            if (pageingQuery != null)
            {

                //BuildQuery();
                pageingQuery.FirstResult = e.NewPageIndex * PAGE_SIZE;
                Query();
            }
        }

        private void btnQuery_Click(object sender, RoutedEventArgs e)
        {
            BuildQuery();
            Query();
        }

        private void btnNewBasic_Click(object sender, RoutedEventArgs e)
        {
            IProduct p = new BasicProduct();
            
            BaseService<TimeUnit> svr=new BaseService<TimeUnit>(LibGlobal.HbmSessionFactory.GetCurrentSession());

            ITimeUnit tu = svr.GetByHQL("from TimeUnit as tu where tu.IsBaseUnit=True");
            p.TimeUnit = tu;

            ProductForm frm = new ProductForm(p);
            frm.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            frm.Owner = LibGlobal.MainWin;
            frm.CallBack = (IProduct p2) =>
            {
                BuildQuery();
                Query();
            };
            frm.Show();
        }

        private void btnNewExtra_Click(object sender, RoutedEventArgs e)
        {
            IProduct p = new ExtraProduct();

            BaseService<TimeUnit> svr = new BaseService<TimeUnit>(LibGlobal.HbmSessionFactory.GetCurrentSession());

            ITimeUnit tu = svr.GetByHQL("from TimeUnit as tu where tu.IsBaseUnit=True");
            p.TimeUnit = tu;

            ProductForm frm = new ProductForm(p);
            frm.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            frm.Owner = LibGlobal.MainWin;
            frm.CallBack = (IProduct p2) =>
                {
                    BuildQuery();
                    Query();
                };
            frm.Show();
        }

        private void btnEdit_Click(object sender, RoutedEventArgs e)
        {
            ViewProduct();
        }

        private void gvProduct_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (PageModel == ListPageModel.List)
            {
                ViewProduct();
            }
            else
            {
                SelectedItem = gvProduct.SelectedItem as IProduct;
                Owner.Close();
            }

        }



        private void btnDel_Click(object sender, RoutedEventArgs e)
        {
            Product p = gvProduct.SelectedItem as Product;

            try
            {
                if (p != null)
                {
                    if (MessageBox.Show(string.Format("是否要删除产品:{0}?删除后不能恢复!", p.Name), "提示", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                    {
                        busyRoot.IsBusy = true;
                        
                        BaseService<Product> svr = new BaseService<Product>(LibGlobal.HbmSessionFactory.GetCurrentSession());

                        svr.Delete(p);

                        Query();
                        busyRoot.IsBusy = false;
                    }
                }
            }
            catch (Exception ex)
            {

                if (busyRoot.IsBusy)
                    busyRoot.IsBusy = false;
                MessageBox.Show(ex.Message, "提示");
            }
        }

        private void ViewProduct()
        {
            IProduct p = gvProduct.SelectedItem as IProduct;

            if (p != null)
            {
                ProductForm frm = new ProductForm(p);
                frm.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                frm.Owner = LibGlobal.MainWin;
                frm.CallBack = (IProduct p2) =>
                {
                    BuildQuery();
                    Query();
                };
                frm.Show();             
            }
        }

        private void LoadCompanies()
        {
            BaseService<Company> svr = new BaseService<Company>(LibGlobal.HbmSessionFactory.GetCurrentSession());

            IList<ICompany> ls = svr.GetListByHQL("from Company Order by Name").Cast<ICompany>().ToList<ICompany>();

            ICompany cmp = new Company();
            cmp.Name = "[全部]";
            cmp.Id = 0;

            ls.Insert(0, cmp);

            cmbCompany.ItemsSource = ls;

            ICompany cp=null;
            if(LibGlobal.GetCurrentCompany!=null)
                cp = LibGlobal.GetCurrentCompany();

            cmbCompany.SelectedItem = cp;

            if (cp != null && cp.Id!=0)
            {
                cmbCompany.IsEnabled = false;
            }
        }

        private void BuildQuery()
        {
            pageingQuery = new PagingQuery();
            pageingQuery.MaxResults = PAGE_SIZE;

            string where = string.Empty;

            if (rbtChecked.IsChecked == true)
                where = " and p.CheckTime is not null";
            else if (rbtUnChecked.IsChecked == true)
                where = " and p.CheckTime is null";

            if (cmbCompany.SelectedItem != null && ((ICompany)cmbCompany.SelectedItem).Id!=0 )
            {
                ICompany c = cmbCompany.SelectedItem as ICompany;

                where += " and p.Company.Id= :companyId";

                pageingQuery.AddParameter("companyId", "int", c.Id.ToString());
            }

            //if (!string.IsNullOrEmpty(txtCatalog.Text))
            //{
            //    where += string.Format(" and p.Catalog Like :catalog");
            //    pageingQuery.AddParameter("catalog", "string", string.Format("%{0}%",txtCatalog.Text.Trim()));
            //}

            if (!string.IsNullOrEmpty(txtName.Text))
            {
                where += string.Format(" and p.Name Like :name");
                pageingQuery.AddParameter("name", "string", string.Format("%{0}%", txtName.Text.Trim()));
            }

            pageingQuery.HQL = hqlBase + where + " order by p.Company.Name,p.Name ";
            pageingQuery.TotalHQL = "select count(*) " + hqlBase + where;
        }

        protected void Query()
        {
            try
            {
                busyRoot.IsBusy = true;
                busyRoot.BusyContent = "正在加载数据...";


                BaseService<Product> svr = new BaseService<Product>(LibGlobal.HbmSessionFactory.GetCurrentSession());

                long total = 0;
                pageingQuery.FirstResult = dpList.PageIndex * PAGE_SIZE;
                IList<Product> ls = svr.GetListByHQLWithPaging(pageingQuery, out total);

                dpList.ItemCount = (int)total;
                gvProduct.ItemsSource = ls;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                busyRoot.IsBusy = false;
            }

        }

        private void btnConfirm_Click(object sender, RoutedEventArgs e)
        {
            if (gvProduct.SelectionMode == SelectionMode.Single)
            {
                SelectedItem = gvProduct.SelectedItem as IProduct;

                if (SelectedItem != null)
                {
                    Owner.Close();
                }
            }
            else
            {
                this.SelectedItems= gvProduct.SelectedItems.Cast<IProduct>();
                if (this.SelectedItems != null)
                {
                    Owner.Close();
                }
            }
        }

        private void btnExit_Click(object sender, RoutedEventArgs e)
        {
            Owner.Close();
        }

        private void SetOperRight()
        {
            btnNewBasic.Visibility = LibGlobal.AppType == AppType.Business ? Visibility.Collapsed : Visibility.Visible;
            btnNewExtra.Visibility = LibGlobal.AppType == AppType.Business ? Visibility.Collapsed : Visibility.Visible;
            btnDel.Visibility = LibGlobal.AppType == AppType.Business ? Visibility.Collapsed : Visibility.Visible;
            spCheck.Visibility = LibGlobal.AppType == AppType.Business ? Visibility.Collapsed : Visibility.Visible;
        }

        private void btnDocFlod_Click(object sender, RoutedEventArgs e)
        {
            IProduct p = gvProduct.SelectedItem as IProduct;

            if (p != null)
            {
                //string path = p.Company.Name + @"\" + p.Name;
                //System.Diagnostics.Process.Start("explorer.exe", path);

                string path = LibGlobal.GetAppPath() + @"\产品介绍\" + p.Company.Name + @"\" + p.Name;
                System.Diagnostics.Process.Start("explorer.exe", path);
            }
        }

        private void TxtQuery_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                BuildQuery();
                Query();
            }
        }

    }
}
